﻿// Extensions Made Easy - Copyright 2012 by Jan Van der Haegen - All rights reserved, use for educational purposes only.
using System;
using System.Globalization;
using ExtensionsMadeEasy.ClientAPI.Navigation;
using ExtensionsMadeEasy.ClientAPI.Utilities.Extensions;
using Microsoft.LightSwitch.ApplicationInfrastructure.Utilities.Internal;
using Microsoft.LightSwitch.BaseServices.Notifications;
using Microsoft.LightSwitch.Runtime.Shell.ViewModels.Notifications;
using Microsoft.LightSwitch.Threading;
using Microsoft.VisualStudio.ExtensibilityHosting;

namespace ExtensionsMadeEasy.Navigation 
{
    public abstract class DeepLinkHandler : ExtensionsMadeEasy.ClientAPI.Utilities.Base.CodeExecuterHook
    {
        private bool handled = false;
        private readonly bool shouldAct;
        private bool refreshed = false;
        protected readonly IEasyNavigationModel navigationModel;

        public DeepLinkHandler()
        {

            this.shouldAct = this.CanNavigate();
            if (this.shouldAct)
            {
                this.GetServiceProxy().NotificationService.Subscribe(typeof(ScreenSelectionChangedNotification), this.OnScreenChanged);
                this.navigationModel = VsExportProviderService.GetExportedValue<IEasyNavigationModel>();           
            }
        }

        public void OnScreenChanged(Notification n)
        {
            if (this.shouldAct && !this.refreshed && !this.handled && this.GetServiceProxy().ActiveScreensViewModel.Current != null)
            {
                ////    //TODO: bug in NavigationViewModel, not all links are loaded on first attempt
                ////    //  => we start a pinger...
                ////    // Only happens if a default screen is set... :-s
                ////TODO according to my "ticket" on MSDN, I should listen to the INotifyPropertyChanged
                ////Try that!
                //TODO Tried that, didn't work :(
                this.refreshed = true;
                BackgroundDispatcher d = new BackgroundDispatcher(CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture, null);
                d.BeginInvoke(delegate()
                {
                    for (int i = 0; i < 40 && !this.handled; i++)
                    {
                        System.Threading.Thread.Sleep(250);
                        this.Execute();
                    }
                }); 
            }
        }

        protected override void Execute()
        {
            if (this.shouldAct && !this.handled)
            {
                try
                {
                    this.handled = this.Navigate();
                }
                catch (Exception)
                {
                }
            }
        }
        protected abstract bool Navigate();
        protected abstract bool CanNavigate();
    }
}